<template>
  <div class="layout-container">
    <el-container style="height: 100vh">
      <el-aside width="220px">
        <div class="logo-container">
          <h2>健身追踪系统</h2>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          :collapse="isCollapse"
          :router="true"
        >
          <!-- 用户界面菜单 -->
          <template v-if="!isAdmin">
            <el-menu-item index="/dashboard">
              <el-icon><Odometer /></el-icon>
              <span>信息总览</span>
            </el-menu-item>
            
            <el-menu-item index="/health-data">
              <el-icon><DataAnalysis /></el-icon>
              <span>健康数据</span>
            </el-menu-item>
            
            <el-sub-menu index="/exercise-records">
              <template #title>
                <el-icon><Timer /></el-icon>
                <span>运动记录</span>
              </template>
              <el-menu-item index="/exercise-records">运动记录列表</el-menu-item>
              <el-menu-item index="/exercise-records/add">添加运动记录</el-menu-item>
            </el-sub-menu>
            
            <el-sub-menu index="/fitness-goals">
              <template #title>
                <el-icon><Trophy /></el-icon>
                <span>健身目标</span>
              </template>
              <el-menu-item index="/fitness-goals">目标列表</el-menu-item>
              <el-menu-item index="/fitness-goals/add">添加目标</el-menu-item>
            </el-sub-menu>
            
            <el-menu-item index="/statistics">
              <el-icon><PieChart /></el-icon>
              <span>数据统计</span>
            </el-menu-item>
            
            <el-menu-item index="/rankings">
              <el-icon><Medal /></el-icon>
              <span>健身排行榜</span>
            </el-menu-item>
          </template>
          
          <!-- 管理员界面菜单 -->
          <template v-else>
            <el-menu-item index="/exercise-types">
              <el-icon><List /></el-icon>
              <span>运动类型管理</span>
            </el-menu-item>
            
            <el-menu-item index="/rankings">
              <el-icon><Medal /></el-icon>
              <span>健身排行榜</span>
            </el-menu-item>
            
            <el-menu-item index="/user-management">
              <el-icon><List /></el-icon>
              <span>用户管理</span>
            </el-menu-item>
            
            <el-menu-item index="/user-exercise-management">
              <el-icon><DataAnalysis /></el-icon>
              <span>用户健身数据</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      
      <el-container>
        <el-header style="height: 50px;">
          <div class="header-left">
            <el-icon 
              class="collapse-btn" 
              @click="toggleSidebar"
            >
              <Fold v-if="!isCollapse" />
              <Expand v-else />
            </el-icon>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index" :to="item.path">
                {{ item.title }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-right">
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="user-dropdown">
                {{ userInfo.fullName || userInfo.username }}
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="password">修改密码</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <el-main>
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
    
    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="passwordForm.currentPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordChange">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Medal, Odometer, DataAnalysis, Timer, List, Trophy, PieChart, Fold, Expand } from '@element-plus/icons-vue'
import { getCurrentUser, changePassword } from '@/api/auth'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const isCollapse = ref(false)
const userInfo = ref({})
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)

const isAdmin = computed(() => {
  return userStore.isAdmin
})

const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})

// 计算面包屑导航
const breadcrumbs = computed(() => {
  const path = route.path
  const title = route.meta.title || '主页'
  
  const result = [
    { path: '/dashboard', title: '首页' }
  ]
  
  if (path !== '/dashboard') {
    result.push({ path: path, title: title })
  }
  
  return result
})

// 切换侧边栏折叠状态
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 下拉菜单命令处理
const handleCommand = (command) => {
  if (command === 'logout') {
    logout()
  } else if (command === 'profile') {
    router.push('/profile')
  } else if (command === 'password') {
    passwordDialogVisible.value = true
  }
}

// 提交修改密码
const submitPasswordChange = async () => {
  try {
    await passwordFormRef.value.validate()
    
    await changePassword({
      currentPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.newPassword
    })
    
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
    passwordForm.value = {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    console.error('修改密码失败:', error)
  }
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.clearLoginInfo()
    router.push('/login')
    ElMessage.success('退出登录成功')
  }).catch(() => {})
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await getCurrentUser()
    userInfo.value = data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.layout-container {
  min-height: 100vh;
}

.el-aside {
  background-color: #304156;
  color: #fff;
  transition: width 0.3s;
}

.logo-container {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 18px;
  border-bottom: 1px solid #1f2d3d;
  background-color: #263445;
}

.logo-container h2 {
  margin: 0;
  font-size: 16px;
}

.el-menu {
  border-right: none;
}

.el-header {
  background-color: #fff;
  color: #303133;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 20px;
}

.header-left, .header-right {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
  cursor: pointer;
  margin-right: 20px;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
}

.el-main {
  padding: 20px;
  background-color: #f0f2f5;
}
</style> 